#include "file_save_util.h"
#include <fcntl.h>
#include <iostream>
#include <fstream>
#include <sys/file.h>
#include <unistd.h>
#include <filesystem>

int FileSaveUtil::saveStrFile(std::string savePath, std::string saveStr)
{
    /// 传入内容空判断....
    if (savePath.length() == 0 || saveStr.length() == 0 || savePath.empty() || saveStr.empty())
    {
        return 0;
    }
    /// save saveStr to savePath
    int fd = open(savePath.c_str(), O_CREAT | O_RDWR);
    int lockSuccess = lockFile(fd, F_WRLCK);

    std::ofstream out(savePath, std::ios::app | std::ios::out);
    if (out.is_open())
    {
        out << saveStr << std::endl;
    }

    int unlockSuccess = lockFile(fd, F_UNLCK);
    out.close();
    close(fd);
    return 1;
}

int FileSaveUtil::lockFile(int fd, short lockType)
{
    struct flock fl = {};
    fl.l_type = lockType;   // 锁类型：F_RDLCK, F_WRLCK, F_UNLCK
    fl.l_whence = SEEK_SET; // 锁定从文件开头计算
    fl.l_start = 0;         // 锁定区域的起点
    fl.l_len = 0;           // 0表示锁定整个文件

    if (fcntl(fd, F_SETLKW, &fl) == -1)
    {
        return 0;
    }
    return 1;
}
